﻿package level4.mo_ui.mo_radio_button {
	import flash.events.EventDispatcher;
	
	import level4.interfaces.dispose.IDisposable;
	import level4.mo_ui.mo_events.MoRadioButtonAdapterEvent;

	/**
	管理 MoRadioButton
	*/
	public class MoRadioButtonGroup extends EventDispatcher implements IDisposable{
		
		private var bts:Array = [];
		private var curSelectedItem:MoRadioButtonAdapter;
		
		public function MoRadioButtonGroup() {
			// constructor code
		}
		//添加一个 监管项
		public function add(item:MoRadioButtonAdapter):void{
			bts.push(item);
			item.addEventListener(MoRadioButtonAdapterEvent.CHANGE,onChange);
		}
		
		public function remove(item:MoRadioButtonAdapter):void{
			var index:int = bts.indexOf(item);
			if(index > -1){
				bts.splice(index,1);
			}
		}
		
		public function removeAll():void{
			bts.length = 0;
			this.curSelectedItem = null;
		}
		public function dispose():void{
			for each(var item:MoRadioButtonAdapter in bts){
				item.removeEventListener(MoRadioButtonAdapterEvent.CHANGE,onChange);
				item.dispose();
			}
			removeAll();
		}
		///////////////////////
		//Getter Setter
		///////////////////////
		public function get selected():MoRadioButtonAdapter{
			return this.curSelectedItem;
		}
		public function set selected(item:MoRadioButtonAdapter):void{
			var e:MoRadioButtonAdapterEvent = new MoRadioButtonAdapterEvent(MoRadioButtonAdapterEvent.CHANGE,item);
			onChange(e);
		}
		
		//////////////////////////
		//事件
		//////////////////////////
		private function onChange(e:MoRadioButtonAdapterEvent):void{
			for each(var item:MoRadioButtonAdapter in bts){
				item.Selected = false;
			}
			var index:int = bts.indexOf(e.selectedItem);
			if(index > -1){
				bts[index].Selected = true;
				this.curSelectedItem = e.selectedItem;
			}
			dispatchEvent(new MoRadioButtonAdapterEvent(MoRadioButtonAdapterEvent.CHANGE,e.selectedItem));
		}
		
	}
	
}
